// package: rewords-server-2024
// filename: admin
// author: diogoxiang@gmail.com
// time: 2024/11/21 09:26

package admin

import (
	"context"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/util/gconv"
	"go.mongodb.org/mongo-driver/bson"

	"rewords-server-2024/internal/consts"
	"rewords-server-2024/internal/library/contexts"
	"rewords-server-2024/internal/model"
	"rewords-server-2024/internal/model/entity"
	"rewords-server-2024/internal/service"
)

type sSysAdmin struct{}

func NewSysAdmin() *sSysAdmin {
	return &sSysAdmin{}
}

func init() {
	service.RegisterSysAdmin(NewSysAdmin())
}

// BindUserContext 绑定用户上下文
func (s *sSysAdmin) BindUserContext(ctx context.Context, user *model.Identity) (err error) {

	// 查询用户信息
	result, err := service.Mgx().FindOne(ctx, consts.CsysUser, bson.M{
		"uid": user.Uid,
	}, nil)

	var adminUser entity.SysAdminUser

	if err = gconv.Struct(result, &adminUser); err != nil {
		return gerror.NewCode(gcode.CodeNotImplemented)
	}

	if adminUser.Status != consts.StatusDisable {
		return gerror.NewCode(gcode.CodeNotImplemented, "用户状态异常")
	}

	user = &model.Identity{
		Uid:    adminUser.Uid,
		App:    adminUser.App,
		Status: adminUser.Status,
		Role:   adminUser.Role,
		Openid: adminUser.OpenId,
		//Level:  ufun.If(adminUser.Level, 0),
		//Points: adminUser.Points,
	}

	contexts.SetUser(ctx, user)
	return
}
